package com.example.zuoye.controller;

import com.example.zuoye.entity.Good;
import com.example.zuoye.service.GoodService;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/good")
public class ShopBackController {

    @Autowired
    private GoodService goodService;

    // 引用ZuoyeApplication下的uploadPathImg
    @Value("${uploadPathImg}")
    private String uploadPathImg;

    /**
     * 后台商品管理界面
     * @param model
     * @return goodManage
     */
    @RequestMapping("/goodManage")
    public String goodManage(Model model){
        // 进入时,从数据库导入所有商品信息
        List<Good> goods = goodService.selectGoodInfo();
        List goodsInfo = new ArrayList();
        List goodInfo = new ArrayList();
        for(int i = 0;i < goods.size();i++){
            List goodTarget = new ArrayList();
            goodTarget.add(goods.get(i).getGood_name());    // 商品名称
            goodTarget.add(goods.get(i).getGood_price());   // 商品价格
            goodTarget.add(goods.get(i).getGood_introduce());  // 商品介绍
            goodTarget.add(goods.get(i).getGood_date());    // 发布日期
            goodTarget.add(goods.get(i).getGood_number());  // 商品数量
            goodTarget.add(goods.get(i).getGood_image());   // 商品图片
            goodTarget.add(goods.get(i).getGood_id());      // 商品id号
            goodInfo.add(goodTarget);
        }
        goodsInfo.add(goodInfo);

        // 将商品信息goodInfo传递给goodManage前端
        model.addAttribute("goodsInfo",goodInfo);
        return "goodManage";
    }

    /**
     * 访问good/addGood时,返回addGood前端页面
     * @return addGood
     */
    @RequestMapping("/addGood")
    public String addGood(){
        return "addGood";
    }

    // 全局gobal_good_id
    private Integer gobal_good_id;

    /**
     * 接收来自前端的 good/modifyGood 访问路径中的参数,依次赋值给good_name,good_introduce,good_price,good_date,good_number
     * @param good_name
     * @param good_introduce
     * @param good_price
     * @param good_date
     * @param good_number
     * @param model
     * @return modifyGood
     * @throws JSONException
     */
    @RequestMapping(value = "/modifyGood")
    public String modifyGood(String good_name,
                             String good_introduce,
                             String good_price,
                             String good_date,
                             Integer good_number,
                             Model model) throws JSONException {

        System.out.println("执行力modifyGood");

        // 定义JSON方式的goodInfo,并将商品信息存入
        JSONObject goodInfo = new JSONObject();
        System.out.println("good_name="+good_name);
        System.out.println("good_introduce="+good_introduce);
        System.out.println("good_price="+good_price);
        System.out.println("good_date="+good_date);
        System.out.println("good_number="+good_number);
        goodInfo.put("good_name",good_name);
        goodInfo.put("good_introduce",good_introduce);
        goodInfo.put("good_price",good_price);
        goodInfo.put("good_date",good_date);
        goodInfo.put("good_number",good_number);

        System.out.println(goodInfo.getInt("good_number"));
        // 将商品信息goodInfo传递给modifyGood前端页面
        model.addAttribute("goodInfo",goodInfo);
        return "modifyGood";
    }

    /**
     * 在访问modifyGood页面之前,先通过bmodifyGood获取goodManage页面点击的good_id值
     * @param good_id
     * @return null
     */
    @RequestMapping("/bmodifyGood")
    @ResponseBody
    public String bmodifyGood(@RequestParam(value = "good_id") Integer good_id){
        System.out.println("执行了bmodifyGood");
        gobal_good_id = good_id;
        System.out.println(gobal_good_id);
        return null;
    }

    /**
     * 当修改页面点击提交时,执行umodifyGood,获取前端商品信息,并修改数据库中对应的商品信息
     * @param file
     * @param request
     * @return redirect:/good/goodManage
     * @throws JSONException
     * @throws IOException
     */
    @RequestMapping(value = "/umodifyGood")
    public String umodifyGood(@RequestParam(value = "good_image") MultipartFile file,
                              HttpServletRequest request) throws JSONException, IOException {
        System.out.println("执行了umodifyGood");

        Integer good_id = gobal_good_id;
        String good_name = request.getParameter("good_name");
        String good_introduce = request.getParameter("good_introduce");
        String good_price = request.getParameter("good_price");
        String good_date = request.getParameter("good_date");
        Integer good_number = Integer.valueOf(request.getParameter("good_number"));
        // 获取前端页面的图片信息
        String good_image = file.getOriginalFilename();

        // 根据当前时间和图片本身名称形成新的图片名称
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        // 图片上次路径位uploadPathImg中定义的路径
        String upload_file_dir = uploadPathImg;

        File upload_file_dir_file = new File(upload_file_dir);

        // 前端上传的文件复制到希望的位置
        File targetFile = new File(upload_file_dir_file, fileName);
        file.transferTo(targetFile);

        // 上传图片最终的路径(String类型)
        good_image = fileName;

        // 传入数据库,根据good_id查找,修改good_id对应的商品信息
        goodService.updateGoodInfoById(good_id,good_name,good_introduce,good_price,good_date,good_number,good_image);

        return "redirect:/good/goodManage";
    }


    /**
     * Post方法,根据图片id删除对应的图片信息
     * @param good_id
     * @return result.toString() Json格式的图片删除信息,成功:success,失败:fail
     * @throws JSONException
     */
    @RequestMapping(value = "/udeleteGood",method = RequestMethod.POST)
    @ResponseBody
    public String udeleteGood(@RequestParam(value = "good_id") Integer good_id) throws JSONException {
        System.out.println("执行了udeleteGood");
        System.out.println(good_id);
        // 删除数据库中对应的图片信息
        Integer delete_result = goodService.deleteGoodInfoById(good_id);

        JSONObject result = new JSONObject();
        if(delete_result != null) {
            System.out.println("delete_result执行成功");
            result.put("status", "success");
        }
        else {
            System.out.println("delete_result执行失败");
            result.put("status", "fail");
        }
        System.out.println(result.toString());
        return result.toString();
    }

    /**
     * POST方法,添加图片信息
     * @param file
     * @param request
     * @return "redirect:/good/goodManage" 返回goodManage页面
     * @throws Exception
     */
    @RequestMapping(value = "/uaddGood",method = RequestMethod.POST)
    public ModelAndView uaddGood(@RequestParam(value = "good_image") MultipartFile file,
                                 HttpServletRequest request) throws Exception{

        System.out.println("执行了uaddGood");

        String good_name = request.getParameter("good_name");
        String good_introduce = request.getParameter("good_introduce");
        String good_price = request.getParameter("good_price");
        String good_date = request.getParameter("good_date");
        Integer good_number = Integer.valueOf(request.getParameter("good_number"));
        String good_image = file.getOriginalFilename();


        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/good/goodManage");

        if (good_name == null || good_introduce == null) {
            mv.addObject("tips","商品名称或作者不能为空");
            return mv;
        }else{
            try {
                if (file != null) {
                    String fileName = System.currentTimeMillis() + file.getOriginalFilename();
                    String upload_file_dir = uploadPathImg;
                    // String destFileName = uploadPathImg + fileName;

                    // 若文件不存在,则创建
                    File upload_file_dir_file = new File(upload_file_dir);
                    if (!upload_file_dir_file.exists()) {
                        upload_file_dir_file.mkdirs();
                    }

                    // 前端上传的文件复制到希望的位置
                    File targetFile = new File(upload_file_dir_file, fileName);
                    file.transferTo(targetFile);

                    // 上传图片最终的路径(String类型)
                    good_image = fileName;

                    // 插入数据库
                    goodService.insertGoodInfo(good_name,good_introduce,good_price,good_date,good_number,good_image);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return mv;
    }
}
